import React, { FC } from 'react';
import { random } from './utils';

interface AuthListItem {
  GroupOutId: string;
  Button: string;
  IsHavePerm: boolean;
}

interface AuthButtonProps {
  operation: Array<any>;
  auth: string;
  type: string;
  authType?: string;
  authList?: Array<AuthListItem>;
}

const AuthButton: FC<AuthButtonProps> = ({
  children,
  authType,
  operation,
  auth,
  authList,
  type,
}) => {
  const row = (operation || []).filter((t) => t[authType || 'operationType'] === type)[0];

  const operationFlagList = (authList || []).filter(
    (ele) => ele.GroupOutId === auth && ele.Button === row?.operationflag,
  );

  const renderEle = React.Children.map(children, (item) => {
    return React.cloneElement(item, {
      ...item.props,
      operationflag: row?.operationflag || '',
      key: random(),
    });
  });

  const shouldRender =
    authList?.length === 0 || operationFlagList.length === 0
      ? true
      : operationFlagList[0]?.IsHavePerm;
  return shouldRender && renderEle;
};

export default AuthButton;
